<template>
  <div class="dashboardPage">
    <div class="top">
      <HomeCard
        v-for="item in cardList"
        :key="item.value"
        :card-data="item"
        :title="item.title"
        :color="item.color"
        :background-color="item.background"
        :today-color="item.todayColor"
        class="cardbox"
      />
    </div>
    <div class="chartContainer">
      <h2>当日订单金额</h2>
      <div ref="chartMoney" class="chartMoney"></div>
      <h2>数据统计</h2>
      <div class="chartCard">
        <div class="dailyCard">
          <div class="cardContainer">
            <MiniCard
              :title="'当日订单数'"
              :precent="'日同比'"
              :nums="orderData.dayNum"
              :precent-data="orderData.dayPrecent"
            />
            <MiniCard
              :title="'当月订单数'"
              :precent="'月同比'"
              :nums="orderData.mounthNum"
              :precent-data="orderData.mounthPrecent"
            />
          </div>
          <div ref="orderTotal" class="chart"></div>
        </div>
        <div class="dailyCard">
          <div class="cardContainer">
            <MiniCard
              :title="'当日支付人数'"
              :precent="'日同比'"
              :nums="payData.dayNum"
              :precent-data="payData.dayPrecent"
            />
            <MiniCard
              :title="'当月支付人数'"
              :precent="'月同比'"
              :nums="payData.mounthNum"
              :precent-data="payData.mounthPrecent"
            />
          </div>
          <div ref="orderPeople" class="chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue'
  import { homeGetChartData, homeGetFormData } from '@/api/home'
  import type { HomeFormData, HomeChartData } from '@/api/model/homeModel'
  import * as echarts from 'echarts'
  import { useSettingStore } from '@/store/modules/setting'
  import { scrollToTop } from '@/utils/utils'
  import HomeCard from './components/HomeCard.vue'
  import MiniCard from './components/miniCard.vue'

  const settingStore = useSettingStore()
  const currentGlopTheme = computed(() => settingStore.systemThemeType)

  // 系统主题风格变化时，刷新页面重写渲染 Echarts
  watch(
    currentGlopTheme,
    () => {
      settingStore.reload()
    },
    { immediate: false }
  )

  // 清理监听器
  onMounted(() => {
    scrollToTop()
  })

  // 定义卡片数据类型
  interface CardItem {
    title: string
    color: string
    background: string
    todayColor: string
    nums: string | number
    precent: number
    lastNums: string | number
    value: number
  }

  // 卡片数据
  const cardList = ref([
    {
      title: '新增用户',
      color: 'var(--art-primary)',
      background: 'var(--art-gray-50)',
      todayColor: 'var(--art-gray-100)',
      nums: '',
      precent: 0,
      lastNums: '',
      value: 1
    },
    {
      title: '新增店铺',
      color: 'var(--art-warning)',
      background: 'var(--art-warning-light-9)',
      todayColor: 'var(--art-warning-light-7)',
      nums: '',
      precent: 0,
      lastNums: '',
      value: 2
    },
    {
      title: '访客',
      color: 'var(--art-success)',
      background: 'var(--art-success-light-9)',
      todayColor: 'var(--art-success-light-7)',
      nums: '',
      precent: 0,
      lastNums: '',
      value: 3
    },
    {
      title: '浏览量',
      color: 'var(--art-info)',
      background: 'var(--art-info-light-9)',
      todayColor: 'var(--art-info-light-7)',
      nums: '',
      precent: 0,
      lastNums: '',
      value: 4
    }
  ])

  // 定义图表对象类型
  interface ChartObjType {
    name: string
    chart: any
    title: string
    xAxis: string[]
    yAxis: any[]
    series: number[]
  }

  // 定义统计数据类型
  interface CardDataType {
    dayNum: number
    dayPrecent: number
    mounthNum: number
    mounthPrecent: number
  }

  // 图表数据
  const chart = ref<ChartObjType[]>([
    ChartObj('chartMoney', '订单金额'),
    ChartObj('orderTotal', '订单数'),
    ChartObj('orderPeople', '订单支付人数')
  ])

  // 统计数据
  const orderData = ref<CardDataType>(CardData())
  const payData = ref<CardDataType>(CardData())

  // 图表引用
  const chartMoney = ref<HTMLElement>()
  const orderTotal = ref<HTMLElement>()
  const orderPeople = ref<HTMLElement>()
  let chartList: { [key: string]: any }

  onMounted(() => {
    chartList = {
      chartMoney,
      orderTotal,
      orderPeople
    }
    getFormData()
    getChartData()
    chart.value.forEach((item: any) => {
      initChart(item)
    })

    // 添加调试信息
    console.log('初始化 订单数据:', orderData.value)
    console.log('初始化 支付人数数据:', payData.value)
  })

  // 获取卡片数据
  function getFormData(): void {
    homeGetFormData().then((res: { data: HomeFormData }) => {
      cardList.value[0] = Object.assign(cardList.value[0], {
        nums: res.data.todayNewUser,
        precent: res.data.weekRelativeRatioNewUser,
        lastNums: res.data.yesterdayNewUser
      })
      cardList.value[1] = Object.assign(cardList.value[1], {
        nums: res.data.todayShopCount,
        precent: res.data.weekRelativeRatioShopCount,
        lastNums: res.data.yesterdayShopCount
      })
      cardList.value[2] = Object.assign(cardList.value[2], {
        nums: res.data.todayVisitUser,
        precent: res.data.weekRelativeRatioVisitUser,
        lastNums: res.data.yesterdayVisitUser
      })
      cardList.value[3] = Object.assign(cardList.value[3], {
        nums: res.data.todayVisitCount,
        precent: res.data.weekRelativeRatioVisitCount,
        lastNums: res.data.yesterdayVisitCount
      })
    })
  }

  // 获取图表数据
  function getChartData(): void {
    homeGetChartData()
      .then((res: { data: HomeChartData }) => {
        console.log('获取图表数据:', res.data)

        // 过去一个月订单金额列表
        res.data.orderAmountList.forEach((item) => {
          if (!item.statsDate.split) {
            return
          }
          const xAxis = `${item.statsDate.split('-')[1]}.${item.statsDate.split('-')[2]}`
          chart.value[0].xAxis.push(xAxis)
          chart.value[0].series.push(item.amount)
        })
        // 过去一个月订单量
        res.data.orderCountList.forEach((item) => {
          if (!item.statsDate.split) {
            return
          }
          const xAxis = `${item.statsDate.split('-')[1]}.${item.statsDate.split('-')[2]}`
          chart.value[1].xAxis.push(xAxis)
          chart.value[1].series.push(item.totalCount)
        })
        // 过去一个月支付人数
        res.data.payUserCountList.forEach((item) => {
          if (!item.statsDate.split) {
            return
          }
          const xAxis = `${item.statsDate.split('-')[1]}.${item.statsDate.split('-')[2]}`
          chart.value[2].xAxis.push(xAxis)
          chart.value[2].series.push(item.totalCount)
        })

        // 更新统计数据
        orderData.value = {
          dayNum: res.data.todayOrderCount || 0,
          dayPrecent: res.data.dayToDayOrderCountRelativeRate || 0,
          mounthNum: res.data.curMonthOrderCount || 0,
          mounthPrecent: res.data.monthToMonthOrderCountRelativeRate || 0
        }
        payData.value = {
          dayNum: res.data.todayPayUserCount || 0,
          dayPrecent: res.data.dayToDayPayUserCountRelativeRate || 0,
          mounthNum: res.data.curMonthPayUserCount || 0,
          mounthPrecent: res.data.monthToMonthPayUserCountRelativeRate || 0
        }

        console.log('更新订单数据:', orderData.value)
        console.log('更新支付人数数据:', payData.value)

        paintLineChart(chart.value[0])
        paintLineChart(chart.value[1])
        paintLineChart(chart.value[2])
      })
      .catch((error) => {
        console.error('获取图表数据失败:', error)
      })
  }

  // 初始化图表
  function initChart(chartObj: ChartObjType): void {
    if (!chartList[chartObj.name].value) {
      console.warn(`Chart container ${chartObj.name} not found`)
      return
    }
    chartObj.chart = echarts.init(chartList[chartObj.name].value)
    chartObj.chart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}',
        axisPointer: {
          type: 'cross'
        }
      }
    })
  }

  // 绘制折线图
  function paintLineChart(chartObj: ChartObjType): void {
    if (!chartObj.chart) {
      console.warn(`Chart instance for ${chartObj.name} not initialized`)
      return
    }
    chartObj.chart.setOption({
      color: ['#5470c6'],
      xAxis: {
        type: 'category',
        axis: 'auto',
        data: chartObj.xAxis,
        axisLine: {
          show: true,
          lineStyle: {
            color: '#ccc'
          }
        },
        axisTick: {
          show: false
        }
      },
      yAxis: {
        type: 'value',
        axisPointer: {
          snap: true
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#ccc'
          }
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed'
          }
        }
      },
      series: [
        {
          name: chartObj.title,
          data: chartObj.series,
          type: 'line',
          smooth: true,
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(84, 112, 198, 0.3)' // 靠近折线的颜色较深
                },
                {
                  offset: 1,
                  color: 'rgba(84, 112, 198, 0.05)' // 远离折线的颜色较浅
                }
              ]
            }
          }
        }
      ]
    })
  }

  // 图表对象构造函数
  function ChartObj(ref: string, title: string): ChartObjType {
    return {
      name: ref,
      chart: null,
      title: title,
      xAxis: [],
      yAxis: [],
      series: []
    }
  }

  // 卡片数据构造函数
  function CardData(): CardDataType {
    return {
      dayNum: 0,
      dayPrecent: 0,
      mounthNum: 0,
      mounthPrecent: 0
    }
  }
</script>

<style lang="scss" scoped>
  .dashboardPage {
    width: 100%;

    .top {
      padding: 28px 10px;
      background-color: var(--art-main-bg-color);
      display: flex;
      justify-content: space-between;

      .cardbox {
        margin: 0 10px;
        cursor: default;
        flex: 1;
      }
    }

    .chartContainer {
      margin: 20px;
      padding: 20px;
      background-color: var(--art-main-bg-color);

      h2 {
        margin: 12px 0;
        font-weight: bold;
        color: var(--art-text-color-primary);
      }

      .chartMoney {
        width: 100%;
        height: 400px;
      }

      .chartCard {
        min-height: 300px;
        display: flex;

        .dailyCard {
          flex: 1;
          padding: 12px 20px;

          .cardContainer {
            display: flex;
          }

          .chart {
            min-height: 300px;
          }
        }
      }
    }
  }
</style>

<!-- 移动端处理 -->
<style lang="scss" scoped>
  .dashboardPage {
    @media screen and (max-width: $device-ipad-pro) {
      .top {
        flex-wrap: wrap;
        margin: 0 -5px; /* 负边距抵消容器的padding */

        .cardbox {
          width: calc(50% - 10px); /* 调整宽度计算 */
          margin: 0 5px 20px 5px; /* 均匀的边距 */
        }
      }

      .chartContainer {
        .chartMoney {
          height: 300px;
        }

        .chartCard {
          flex-wrap: wrap;

          .dailyCard {
            width: 100%;
            margin-bottom: 20px;
          }
        }
      }
    }

    @media screen and (max-width: $device-ipad-vertical) {
      .top {
        flex-direction: column;
        margin: 0; /* 重置负边距 */

        .cardbox {
          width: 100%;
          margin: 0 0 20px 0; /* 只保留底部边距 */
        }
      }

      .chartContainer {
        margin: 10px;
        padding: 10px;

        .chartMoney {
          height: 250px;
        }
      }
    }

    @media screen and (max-width: $device-phone) {
      .top {
        flex-direction: column;
        margin: 0;
        padding: 10px 5px; /* 重置水平内边距，避免右侧空白 */

        .cardbox {
          width: 100%;
          margin: 0 0 10px 0;
        }
      }

      .chartContainer {
        margin: 10px 5px;
        padding: 10px 5px;

        .chartMoney {
          height: 200px;
        }

        .chart {
          height: 200px;
        }
      }
    }

    /* 针对超小屏幕手机的额外优化 */
    @media screen and (max-width: 400px) {
      .top {
        padding: 10px 5px;
        margin: 0;

        .cardbox {
          width: 100%;
          margin: 0 0 10px 0;
        }
      }

      .chartContainer {
        margin: 5px 5px;
        padding: 5px 5px;

        .chartMoney {
          height: 180px;
        }

        .chart {
          height: 180px;
        }
      }
    }
  }
</style>
